/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import java.awt.Color;
import java.awt.HeadlessException;
import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Timer;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import util.BackupFilesTask;
import util.Dados;
import util.FileZipBackup;
import util.PropertiesUtil;

/**
 *
 * @author boskyn9
 */
public class MainFrame extends javax.swing.JFrame{

    /**
     * Creates new form MainFrame
     */
    private Dados dados;
    NumberFormat format = new DecimalFormat(",###");
    BackupFilesTask task = null;
    boolean linhaDeComando = false;
    
    public MainFrame(Dados dados) {
        initComponents();
        this.getRootPane().setDefaultButton(jButton3);
        if(dados==null){            
            this.setVisible(true);
            PropertiesUtil.getDados();
            this.dados = Dados.getDados();
        }else{
            this.dados = dados;
            this.linhaDeComando = true;
            System.out.println("linha de comando");
            System.out.println(dados);            
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    public void setDados(Dados dados){
        this.dados = dados;
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        FileSelector = new javax.swing.JFileChooser();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField_origem = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jTextField_destino = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextField_vida = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        situacao = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Backup File v.1.0");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jLabel1.setText("Origem:");

        jLabel2.setText("Destino:");

        jButton1.setText("...");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("...");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTextArea1.setEditable(false);
        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.setCaretPosition(jTextArea1.getDocument().getLength());
        jScrollPane1.setViewportView(jTextArea1);

        jPanel1.setBackground(new java.awt.Color(255, 255, 204));

        jLabel3.setText("Tempo para criação:");

        jLabel4.setText("seg");

        jLabel5.setText("Tempo de vida:");

        jTextField_vida.setToolTipText("Não preencha, caso não queira apagar os arquivos.");

        jLabel6.setText("seg");

        jButton4.setText("Arquivos");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Parar");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE)
                    .addComponent(jTextField_vida))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jButton4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jTextField_vida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(jButton5))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jButton3.setText("Iniciar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        situacao.setForeground(Color.RED);
        situacao.setText("parado...");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 402, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextField_destino)
                            .addComponent(jTextField_origem))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(situacao)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField_origem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField_destino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(situacao)
                .addContainerGap(32, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-430)/2, (screenSize.height-393)/2, 430, 393);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        FileSelector.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);        
        FileSelector.showOpenDialog(this);
        File file = FileSelector.getSelectedFile();
        if(file !=null){
            dados.setOrigem(file.getAbsolutePath());
            jTextField_origem.setText(dados.getOrigem());
            //TODO salvar em propertie
        }else{
            //TODO erro no log
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        FileSelector.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);        
        FileSelector.showOpenDialog(this);
        File file = FileSelector.getSelectedFile();
        if(file !=null){
            dados.setDestino(file.getAbsolutePath());
            jTextField_destino.setText(dados.getDestino());
            //TODO salvar em propertie
        }else{
            //TODO erro no log
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        start();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        if(dados.getDestino()!=null && !dados.getDestino().isEmpty()){
            jTextField_destino.setText(dados.getDestino());
        }
        if(dados.getOrigem()!=null && !dados.getOrigem().isEmpty()){
            jTextField_origem.setText(dados.getOrigem());
        }
        if(dados.getTime()!=null){
            jTextField1.setText(dados.getTime()+"");
        }
        if(dados.getTempoVida()!=null){
            jTextField_vida.setText(dados.getTempoVida()+"");
        }
        
        if(linhaDeComando){
            System.out.println("linha de comando");
            this.start();
        }else{
            System.out.println("n linha de comando");
        }
        
    }//GEN-LAST:event_formWindowOpened

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        jTextArea1.append("---------------------------\n");
        File dir = new File(dados.getDestino());
        File[] files = dir.listFiles(new FileZipBackup());
        long totalSize = 0;
        for (int i = 0; i < files.length; i++) {
            totalSize += files[i].length()/1024;
            jTextArea1.append(files[i].getName()+" - "+format.format(files[i].length()/1024)+" MB");
            jTextArea1.append("\n");
        }
        jTextArea1.append("total: "+files.length+" arquivos, "+format.format(totalSize) +"MB \n");
        jTextArea1.append("---------------------------\n");
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        stop();
    }//GEN-LAST:event_jButton5ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
            }
            
            
            System.out.println(String.format("args - %s", args.length));
            Dados dados = null;
            if(args.length > 0 && args.length < 5){
                dados = Dados.getDados();
                dados.setOrigem(args[0]);
                dados.setDestino(args[1]); 
                dados.setTime(Long.parseLong(args[2]));
                dados.setTempoVida(Long.parseLong(args[3]));                
            }else{
                System.out.println("arg 1 - origem;");
                System.out.println("arg 2 - destino;");
                System.out.println("arg 3 - tempo;");
                System.out.println("arg 4 - tempo de vida;");
            }
            
            MainFrame mainFrame = new MainFrame(dados);
//            new Thread(mainFrame).start();
            
        } catch (Exception ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } 
        
        
                
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFileChooser FileSelector;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField_destino;
    private javax.swing.JTextField jTextField_origem;
    private javax.swing.JTextField jTextField_vida;
    private javax.swing.JLabel situacao;
    // End of variables declaration//GEN-END:variables

    private void start(){
        dados.setOrigem(jTextField_origem.getText());
        dados.setDestino(jTextField_destino.getText());
        
        
        Long tempo = null;
        try {
            tempo = Long.parseLong(jTextField1.getText());
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Digite um valor válido no tempo. ("+jTextField1.getText()+")");
        }
        
        Long tempoVida = -1l;
        if(!jTextField_vida.getText().isEmpty()){
            try {
                tempoVida = Long.parseLong(jTextField_vida.getText());
                if(tempoVida < 0){
                    JOptionPane.showMessageDialog(this, "O tempo de vida deve ter um valor maior que zero.");
                    tempoVida = null;
                }
            } catch (NumberFormatException | HeadlessException e) {
                JOptionPane.showMessageDialog(this, "Digite um valor válido no tempo de vida.");
            }
        }
        
        
        if(tempo !=null && tempoVida !=null){
            dados.setTime(tempo);
            dados.setTempoVida(tempoVida);
            
            try {
                task = new BackupFilesTask(jTextArea1);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Obrigatoriamente deve definir os campos de origem e destino.\n"+ex.toString());                
            }
        
            if(task!=null){
                PropertiesUtil.setDados(dados);
                Timer timer = new Timer("Backup File");
                timer.scheduleAtFixedRate(task,0, 1000*tempo);
                
            }
        }else{
            JOptionPane.showMessageDialog(this, "Operação não iniciada.");
        }
        
        jTextField1.setEnabled(false);
        jTextField_vida.setEnabled(false);
        
        situacao.setText("rodando...");
        situacao.setForeground(new Color(0, 102, 51));
    }
    
    private void stop(){
        // TODO add your handling code here:
        if(task!=null){
            task.cancel();
        }
        jTextField1.setEnabled(true);
        jTextField_vida.setEnabled(true);
        
        situacao.setText("parado...");
        situacao.setForeground(Color.RED);
    }

}
